<template>
  <div class="page-container">
    <h2>用户管理</h2>
    
    <!-- 搜索表单 -->
    <el-form :model="searchForm" inline class="search-form">
      <el-form-item label="用户信息">
        <el-input v-model="searchForm.userInfo" placeholder="请输入用户信息" clearable />
      </el-form-item>
      <el-form-item label="用户等级">
        <el-select v-model="searchForm.userLevel" placeholder="请选择用户等级" clearable>
          <el-option label="普通用户" :value="1" />
          <el-option label="会员" :value="2" />
        </el-select>
      </el-form-item>
      <el-form-item label="用户状态">
        <el-select v-model="searchForm.userState" placeholder="请选择用户状态" clearable>
          <el-option label="正常" :value="1" />
          <el-option label="禁用" :value="0" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="handleSearch">
          <el-icon><Search /></el-icon>
          搜索
        </el-button>
        <el-button @click="handleReset">
          <el-icon><Refresh /></el-icon>
          重置
        </el-button>
      </el-form-item>
      <div style="margin-left:auto;">
        <el-button type="success" @click="handleAdd">
          <el-icon><Plus /></el-icon>
          新增用户
        </el-button>
      </div>
    </el-form>

    <!-- 数据表格 -->
    <el-table 
      :data="displayedData" 
      v-loading="loading"
      class="table-container"
      border
      stripe
    >
      <template #empty>
        <div style="padding: 24px; color: #909399;">暂无数据</div>
      </template>
      <el-table-column prop="userId" label="用户ID" width="80" />
      <el-table-column prop="userInfo" label="用户信息" min-width="200" />
      <el-table-column prop="userLevel" label="用户等级" width="100">
        <template #default="{ row }">
          <el-tag :type="getLevelTagType(row.userLevel)">
            {{ getLevelText(row.userLevel) }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="costNum" label="消费次数" width="100" />
      <el-table-column prop="costMoney" label="消费金额" width="120">
        <template #default="{ row }">
          ¥{{ row.costMoney?.toFixed(2) || '0.00' }}
        </template>
      </el-table-column>
      <el-table-column prop="userState" label="用户状态" width="100">
        <template #default="{ row }">
          <el-tag :type="row.userState === 1 ? 'success' : 'danger'">
            {{ row.userState === 1 ? '正常' : '禁用' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="createTime" label="创建时间" width="180">
        <template #default="{ row }">
          {{ formatDate(row.createTime) }}
        </template>
      </el-table-column>
      <el-table-column label="操作" width="200" fixed="right">
        <template #default="{ row }">
          <el-button type="primary" size="small" @click="handleEdit(row)">
            <el-icon><Edit /></el-icon>
            编辑
          </el-button>
          <el-button type="danger" size="small" @click="handleDelete(row)">
            <el-icon><Delete /></el-icon>
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <div style="margin-top: 16px; text-align: right;">
      <el-pagination
        background
        layout="total, sizes, prev, pager, next, jumper"
        :total="pagination.total"
        :page-size="pagination.pageSize"
        :current-page="pagination.pageNum"
        :page-sizes="[5,10,20,50]"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>

    <!-- 添加/编辑对话框 -->
    <el-dialog 
      v-model="dialogVisible" 
      :title="dialogTitle"
      width="600px"
      @close="handleDialogClose"
    >
      <el-form 
        ref="formRef"
        :model="formData" 
        :rules="formRules" 
        label-width="100px"
      >
        <el-form-item label="用户信息" prop="userInfo">
          <el-input v-model="formData.userInfo" placeholder="请输入用户信息" />
        </el-form-item>
        <el-form-item label="用户等级" prop="userLevel">
          <el-select v-model="formData.userLevel" placeholder="请选择用户等级">
            <el-option label="普通用户" :value="1" />
            <el-option label="会员" :value="2" />
          </el-select>
        </el-form-item>
        <el-form-item label="消费次数" prop="costNum">
          <el-input-number v-model="formData.costNum" :min="0" />
        </el-form-item>
        <el-form-item label="消费金额" prop="costMoney">
          <el-input-number v-model="formData.costMoney" :min="0" :precision="2" />
        </el-form-item>
        <el-form-item label="用户状态" prop="userState">
          <el-radio-group v-model="formData.userState">
            <el-radio :label="1">正常</el-radio>
            <el-radio :label="0">禁用</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSubmit" :loading="submitLoading">
            确定
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Search, Refresh, Plus, Edit, Delete } from '@element-plus/icons-vue'
import { userApi } from '@/api/user'
import dayjs from 'dayjs'

// 响应式数据
const loading = ref(false)
const submitLoading = ref(false)
const dialogVisible = ref(false)
const dialogTitle = ref('')
const formRef = ref()

// 搜索表单
const searchForm = reactive({
  userInfo: '',
  userLevel: null,
  userState: null
})

// 表格数据
const tableData = ref([])

// 分页
const pagination = reactive({
  pageNum: 1,
  pageSize: 10,
  total: 0
})

// 直接使用服务端返回的数据
const displayedData = computed(() => {
  return tableData.value || []
})

// 表单数据
const formData = reactive({
  userId: null,
  userInfo: '',
  userLevel: 1,
  costNum: 0,
  costMoney: 0,
  userState: 1
})

// 表单验证规则
const formRules = {
  userInfo: [
    { required: true, message: '请输入用户信息', trigger: 'blur' }
  ],
  userLevel: [
    { required: true, message: '请选择用户等级', trigger: 'change' }
  ],
  userState: [
    { required: true, message: '请选择用户状态', trigger: 'change' }
  ]
}

// 获取用户等级文本
const getLevelText = (level) => {
  const levelMap = {
    1: '普通用户',
    2: '会员'
  }
  return levelMap[level] || '未知'
}

// 获取用户等级标签类型
const getLevelTagType = (level) => {
  const typeMap = {
    1: '',
    2: 'success'
  }
  return typeMap[level] || ''
}

// 格式化日期
const formatDate = (date) => {
  return date ? dayjs(date).format('YYYY-MM-DD HH:mm:ss') : '-'
}

// 获取用户列表
const getUserList = async () => {
  try {
    loading.value = true
    const response = await userApi.getUserList({
      ...searchForm,
      page: pagination.pageNum,
      pageSize: pagination.pageSize
    })
    tableData.value = response.data || []
    // 用户管理使用服务端分页，但后端可能没有返回总数，所以使用当前数据长度
    pagination.total = response.total || (Array.isArray(response.data) ? response.data.length : 0)
  } catch (error) {
    ElMessage.error('获取用户列表失败')
  } finally {
    loading.value = false
  }
}

// 搜索
const handleSearch = () => {
  pagination.pageNum = 1
  getUserList()
}

// 重置
const handleReset = () => {
  Object.assign(searchForm, {
    userInfo: '',
    userLevel: null,
    userState: null
  })
  pagination.pageNum = 1
  getUserList()
}

// 新增用户
const handleAdd = () => {
  dialogTitle.value = '新增用户'
  resetFormData()
  dialogVisible.value = true
}

// 编辑用户
const handleEdit = (row) => {
  dialogTitle.value = '编辑用户'
  Object.assign(formData, row)
  dialogVisible.value = true
}

// 删除用户
const handleDelete = async (row) => {
  try {
    await ElMessageBox.confirm('确定要删除该用户吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    
    await userApi.deleteUser(row.userId)
    ElMessage.success('删除成功')
    getUserList()
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('删除失败')
    }
  }
}

// 提交表单
const handleSubmit = async () => {
  try {
    await formRef.value.validate()
    submitLoading.value = true
    
    if (formData.userId) {
      await userApi.updateUser(formData)
      ElMessage.success('修改成功')
    } else {
      await userApi.addUser(formData)
      ElMessage.success('添加成功')
    }
    
    dialogVisible.value = false
    getUserList()
  } catch (error) {
    if (error !== false) {
      ElMessage.error(formData.userId ? '修改失败' : '添加失败')
    }
  } finally {
    submitLoading.value = false
  }
}

// 重置表单数据
const resetFormData = () => {
  Object.assign(formData, {
    userId: null,
    userInfo: '',
    userLevel: 1,
    costNum: 0,
    costMoney: 0,
    userState: 1
  })
}

// 关闭对话框
const handleDialogClose = () => {
  formRef.value?.resetFields()
  resetFormData()
}

// 处理每页显示条数改变
const handleSizeChange = (size) => {
  pagination.pageSize = size
  pagination.pageNum = 1
  getUserList()
}

// 处理当前页改变
const handleCurrentChange = (page) => {
  pagination.pageNum = page
  getUserList()
}

// 初始化
onMounted(() => {
  getUserList()
})
</script>

<style scoped>
.search-form {
  background-color: #f8f9fa;
  padding: 20px;
  border-radius: 8px;
  margin-bottom: 20px;
}

.table-container {
  margin-top: 20px;
}

.dialog-footer {
  text-align: right;
}
</style>
